/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.classcode.enhance.bytebuddy.interceptor;

import com.hyts.guava.object.Objects;
import net.bytebuddy.implementation.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;

/**
 * @project-name:coffice-toolbox
 * @package-name:com.hyts.classcode.enhance.bytebuddy.interceptor
 * @author:LiBo/Alex
 * @create-date:2020-04-23 17:03
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
public class GlobalInterceptor {

    /**
     * 操作处理服务处理
     */
    static MethodFilter methodFilter;

    /**
     * 操作服务处理处理
     * @param method
     * @return
     */
    @RuntimeType
    public static Object intercept(@This Object obj,
                       @AllArguments Object[] allArguments,
                       @SuperCall Callable<?> zuper,
                       @Origin Method method){
        // 前置操作服务
        Object result = null;
        if(Objects.nonNull(methodFilter)){
            methodFilter.before(obj,allArguments,method);
        }
        try {
            // 直接执行调用操作服务
            result =  method.invoke(obj,allArguments);
        } catch (IllegalAccessException | InvocationTargetException e) {
            if(Objects.nonNull(methodFilter)){
                //错误操作服务处理
                methodFilter.error(obj,allArguments,method,e);
            }
        }
        //后置操作服务
        if(Objects.nonNull(methodFilter)){
            methodFilter.after(obj,allArguments,method,result);
        }
        return result;
    }

}
